package com.asset.dispoal.poi.documentation.service.commom;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.asset.dispoal.poi.documentation.domain.db.FeatureTable;
import com.asset.dispoal.poi.documentation.domain.db.FeatureTableExpand;
import com.asset.dispoal.poi.documentation.domain.db.FormulaData;
import com.asset.dispoal.poi.documentation.domain.db.JudicialDocument;
import com.asset.dispoal.poi.documentation.domain.db.JudicialDocumentParam;
import com.asset.dispoal.poi.documentation.domain.db.mapper.DocumentationMapper;
import com.asset.dispoal.poi.documentation.domain.dto.IdCardNo;
import com.asset.dispoal.poi.documentation.dto.AgentRequest;
import com.asset.dispoal.poi.documentation.dto.DocumentationRequest;
import com.asset.dispoal.poi.documentation.service.commom.util.IdcardProUtil;
import com.asset.dispoal.poi.documentation.util.SealPictureRenderPolicy;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.MapAccessor;
import org.springframework.core.env.Environment;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.io.IOUtil;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author qr
 * @date 2022/5/6$z
 */
@Component
public class DownloadDocumentCommand implements BaseCommand<DocumentationRequest, Result> {

    @Autowired
    DocumentationMapper documentationMapper;

    @Autowired
    private BaseIdeable<String> idWorker;

    @Autowired
    private Environment environment;

    @SneakyThrows
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(DocumentationRequest request) {
        //逻辑第一步查询数据
        List<IdCardNo> idCardNoList = null;
        if ("2".equals(request.getMode())) {
            //找到对应的合同号和身份证号
            idCardNoList = EasyExcel.read(request.getFile().getInputStream()).head(IdCardNo.class).sheet().doReadSync();
        }

        List<Map<String, String>> dataMap = documentationMapper.queryDataDetail(request.getAssetInstBatchId());
        List<Map<String, Object>> agreementDataResponseList = documentationMapper.queryResult(request.getAssetInstBatchId(), dataMap, request.getAppointId());
        if (CollectionUtil.isEmpty(agreementDataResponseList)) {
            return Result.faild("处理的数据不存在");
        }
        List<IdCardNo> finalIdCardNoList = idCardNoList;
        agreementDataResponseList = agreementDataResponseList.stream().filter(agreementData -> {
            if (CollectionUtil.isNotEmpty(request.getCaseIdList())) {
                if (request.getCaseIdList().contains(agreementData.get("caseId"))) {
                    return true;
                }
            }
            if (CollectionUtil.isNotEmpty(request.getAgreementIdList())) {
                if (request.getAgreementIdList().contains(agreementData.get("contractId"))) {
                    return true;
                }
            }
            if (CollectionUtil.isNotEmpty(finalIdCardNoList)) {
                Optional<IdCardNo> optional = finalIdCardNoList.stream().filter(idCardNo -> agreementData.get("idcard").equals(idCardNo.getIdCard()) && agreementData.get("no").equals(idCardNo.getNo())).findFirst();
                return optional.isPresent();
            }
            return false;
        }).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(agreementDataResponseList)) {
            return Result.faild("合同数据不存在");
        }
        if (StringUtil.isNotEmpty(request.getSueParameterId())) {
            request.setSueMap(documentationMapper.getFormulaInfoById(request.getSueParameterId()));
        }
        if (StringUtil.isNotEmpty(request.getPlaintiffId())) {
            request.setPlaintiffMap(documentationMapper.getPlaintiffById(request.getPlaintiffId()));
        }

        if (CollectionUtil.isNotEmpty(request.getAgent())) {
            List<Map<String, Object>> agentList = new ArrayList<>();
            List<Map<String, Object>> agentRequestList = documentationMapper.queryAgentByAgentIdList(request.getAgent());

            for (AgentRequest a : request.getAgent()) {
                for (Map<String, Object> agent : agentRequestList) {
                    if (a.getAgentId().equals(agent.get("agentId"))) {
                        Map<String, Object> agentMap = new HashMap<>(agent);
                        agentMap.put("agentType", a.getAgentType());
                        agentList.add(agentMap);
                    }
                }
            }

            request.setAgentList(agentList);
        }

        return encapsulation(agreementDataResponseList, request);
    }


    @SneakyThrows
    private Result encapsulation(List<Map<String, Object>> agreementDataList, DocumentationRequest request) {
        List<Map<String, Object>> outList = new ArrayList<>();
        List<FormulaData> formulaDataList = documentationMapper.queryFormulaData();
        if ("1".equals(request.getFileType())) {
            //司法文书
            JudicialDocument document = documentationMapper.getJudicialDocumentById(request.getTemplateId());
            if (ObjectUtil.isEmpty(document)) {
                return Result.faild("文书或文件不存在");
            }
            ConfigureBuilder configureBuilder = Configure.builder().setValidErrorHandler(new Configure.DiscardHandler()).useSpringEL(false);

            List<JudicialDocumentParam> documentParamList = documentationMapper.queryJudicialDocumentParamByDocumentId(request.getTemplateId());
            Map<Object, List<Map<String, Object>>> agreementIdCardMap = agreementDataList.stream().collect(Collectors.groupingBy(map -> map.get("idcard")));
            Set<Object> idCardKeys = agreementIdCardMap.keySet();
            for (Object idCard : idCardKeys) {
                List<Map<String, Object>> agreementDataIdCardList = agreementIdCardMap.get(idCard);
                if ("1".equals(request.getDownloadType())) {
                    Map<String, Object> map = new HashMap<>(2);
                    Map<String, Object> agreementData = agreementDataIdCardList.get(0);
                    Map<String, List<Object>> idCardSum = new HashMap<>();
                    byte[] templateByte = null;
                    if (CollectionUtil.isNotEmpty(documentParamList)) {
                        Map<String, Object> templateParamMap = new HashMap<>(documentParamList.size());
                        for (JudicialDocumentParam param : documentParamList) {
                            templateParamMap.put(param.getParam(), param.getValue());
                        }
                        Configure templateConfigure = Configure.builder().setValidErrorHandler(new Configure.DiscardHandler()).build();
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        XWPFTemplate.compile(environment.getProperty("file.evidence.url") + document.getFileUrl(), templateConfigure).render(templateParamMap).write(output);
                        templateByte = output.toByteArray();
                    }

                    BigDecimal penaltyInterest = convertFormalData(agreementData, formulaDataList, request);
                    agreementData.put("penaltyInterest", penaltyInterest);

                    BigDecimal creditPrincipalAmount = agreementDataIdCardList.stream().filter(data -> data.get("creditPrincipalAmount") != null).map(data -> (BigDecimal) data.get("creditPrincipalAmount")).reduce(BigDecimal.ZERO, BigDecimal::add);//发放贷款本金金额
                    BigDecimal lawsuitPrincipalAmount = agreementDataIdCardList.stream().filter(data -> data.get("lawsuitPrincipalAmount") != null).map(data -> (BigDecimal) data.get("creditPrincipalAmount")).reduce(BigDecimal.ZERO, BigDecimal::add);//发放贷款本金金额
                    BigDecimal subtract = creditPrincipalAmount.subtract(lawsuitPrincipalAmount);
                    if (lawsuitPrincipalAmount.compareTo(new BigDecimal(0)) == 0) {
                        agreementData.put("performance", "已履约");
                    } else {
                        if (subtract.compareTo(new BigDecimal(0)) == 0) {
                            agreementData.put("performance", "从未履约");
                        } else {
                            agreementData.put("performance", "部分履约");
                        }
                    }

                    for (Map<String, Object> agreementDataIdCard : agreementDataIdCardList) {
                        BigDecimal penaltyInterestDataIdCard = convertFormalData(agreementDataIdCard, formulaDataList, request);
                        agreementDataIdCard.put("penaltyInterest", penaltyInterestDataIdCard);
                        Set<String> keys = agreementDataIdCard.keySet();
                        for (String key : keys) {
                            if (!idCardSum.containsKey(key + "List")) {
                                idCardSum.put(key + "List", new ArrayList<>(agreementDataList.size()));
                            }
                            idCardSum.get(key + "List").add(agreementDataIdCard.get(key));
                        }
                    }
                    agreementData.putAll(idCardSum);
                    agreementData.put("today", DateTimeUtil.currentDate());
                    String sex = "男";
                    if (IdcardProUtil.getSexFromIdCard((String) idCard) == 2) {
                        sex = "女";
                    }

                    agreementData.put("sex", sex);
                    agreementData.put("birthday", IdcardProUtil.getBirthDayFromIdCard((String) idCard));
                    String format = String.format("%s-%s.%s", agreementData.get("borrowerName"), agreementData.get("idcard"), "docx");
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] outByte;
                    if (request.getSeal() == 1) {
                        configureBuilder.setValidErrorHandler(new Configure.ClearHandler());
                        configureBuilder.addPlugin('%', new SealPictureRenderPolicy());
                        if (agreementData.get("image") != null) {
                            agreementData.put("image", environment.getProperty("file.evidence.url") + agreementData.get("image"));
                        }
                    } else {
                        configureBuilder.setValidErrorHandler(new Configure.ClearHandler());
                        agreementData.put("image", null);
                    }
                    if (templateByte == null) {
                        XWPFTemplate.compile(environment.getProperty("file.evidence.url") + document.getFileUrl(), configureBuilder.build()).render(agreementData).write(output);
                    } else {
                        XWPFTemplate.compile(new ByteArrayInputStream(templateByte), configureBuilder.build()).render(agreementData).write(output);
                    }
                    outByte = output.toByteArray();

                    map.put("templateName", format);
                    map.put("outByte", outByte);
                    outList.add(map);
                } else {
                    for (Map<String, Object> agreementData : agreementDataIdCardList) {
                        Map<String, Object> map = new HashMap<>(2);
                        byte[] templateByte = null;
                        if (CollectionUtil.isNotEmpty(documentParamList)) {
                            Map<String, Object> templateParamMap = new HashMap<>(documentParamList.size());
                            for (JudicialDocumentParam param : documentParamList) {
                                templateParamMap.put(param.getParam(), param.getValue());
                            }
                            Configure templateConfigure = Configure.builder().setValidErrorHandler(new Configure.DiscardHandler()).build();
                            ByteArrayOutputStream output = new ByteArrayOutputStream();
                            XWPFTemplate.compile(environment.getProperty("file.evidence.url") + document.getFileUrl(), templateConfigure).render(templateParamMap).write(output);
                            templateByte = output.toByteArray();
                        }

                        BigDecimal creditPrincipalAmount = agreementDataIdCardList.stream().filter(data -> data.get("creditPrincipalAmount") != null).map(data -> (BigDecimal) data.get("creditPrincipalAmount")).reduce(BigDecimal.ZERO, BigDecimal::add);//发放贷款本金金额
                        BigDecimal lawsuitPrincipalAmount = agreementDataIdCardList.stream().filter(data -> data.get("lawsuitPrincipalAmount") != null).map(data -> (BigDecimal) data.get("creditPrincipalAmount")).reduce(BigDecimal.ZERO, BigDecimal::add);//发放贷款本金金额
                        BigDecimal subtract = creditPrincipalAmount.subtract(lawsuitPrincipalAmount);
                        if (lawsuitPrincipalAmount.compareTo(new BigDecimal(0)) == 0) {
                            agreementData.put("performance", "已履约");
                        } else {
                            if (subtract.compareTo(new BigDecimal(0)) == 0) {
                                agreementData.put("performance", "从未履约");
                            } else {
                                agreementData.put("performance", "部分履约");
                            }
                        }
                        BigDecimal penaltyInterest = convertFormalData(agreementData, formulaDataList, request);
                        agreementData.put("penaltyInterest", penaltyInterest);

                        String format = String.format("%s-%s-%s.%s", agreementData.get("borrowerName"), agreementData.get("idcard"), agreementData.get("no"), "docx");
                        agreementData.put("today", DateTimeUtil.currentDate());
                        String sex = "男";
                        if (IdcardProUtil.getSexFromIdCard((String) idCard) == 2) {
                            sex = "女";
                        }
                        agreementData.put("sex", sex);
                        agreementData.put("birthday", IdcardProUtil.getBirthDayFromIdCard((String) idCard));
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        if (request.getSeal() == 1) {
                            configureBuilder.setValidErrorHandler(new Configure.ClearHandler());
                            configureBuilder.addPlugin('%', new SealPictureRenderPolicy());
                            if (agreementData.get("image") != null) {
                                agreementData.put("image", environment.getProperty("file.evidence.url") + agreementData.get("image"));
                            }
                        } else {
                            configureBuilder.setValidErrorHandler(new Configure.ClearHandler());
                            agreementData.put("image", null);
                        }
                        if (templateByte == null) {
                            XWPFTemplate.compile(environment.getProperty("file.evidence.url") + document.getFileUrl(), configureBuilder.build()).render(agreementData).write(output);
                        } else {
                            XWPFTemplate.compile(new ByteArrayInputStream(templateByte), configureBuilder.build()).render(agreementData).write(output);
                        }
                        byte[] outByte = output.toByteArray();
                        map.put("templateName", format);
                        map.put("outByte", outByte);
                        outList.add(map);
                    }
                }
            }
        } else {
            //要素表
            FeatureTable featureTable = documentationMapper.getFeatureTableById(request.getTemplateId());
            if (ObjectUtil.isEmpty(featureTable)) {
                return Result.faild("要素表不存在");
            }
            List<FeatureTableExpand> featureTableExpandList = documentationMapper.queryFeatureTableExpandByTableId(request.getTemplateId());
            Map<Object, List<Map<String, Object>>> agreementIdCardMap = agreementDataList.stream().collect(Collectors.groupingBy(map -> map.get("idcard")));
            Set<Object> idCardKeys = agreementIdCardMap.keySet();
            for (Object idCard : idCardKeys) {
                List<Map<String, Object>> agreementDataIdCardList = agreementIdCardMap.get(idCard);

                Map<String, Object> agreementData = agreementDataIdCardList.get(0);
                Map<String, List<Object>> idCardSum = new HashMap<>();

                BigDecimal penaltyInterest = convertFormalData(agreementData, formulaDataList, request);
                agreementData.put("penaltyInterest", penaltyInterest);

                for (Map<String, Object> agreementDataIdCard : agreementDataIdCardList) {
                    BigDecimal penaltyInterestDataIdCard = convertFormalData(agreementDataIdCard, formulaDataList, request);
                    agreementDataIdCard.put("penaltyInterest", penaltyInterestDataIdCard);
                    Set<String> keys = agreementDataIdCard.keySet();
                    for (String key : keys) {
                        if (!idCardSum.containsKey(key + "List")) {
                            idCardSum.put(key + "List", new ArrayList<>(agreementDataList.size()));
                        }
                        idCardSum.get(key + "List").add(agreementDataIdCard.get(key));
                    }
                }
                agreementData.putAll(idCardSum);
                agreementData.put("today", DateTimeUtil.currentDate());
                String sex = "男";
                if (IdcardProUtil.getSexFromIdCard((String) idCard) == 2) {
                    sex = "女";
                }
                agreementData.put("sex", sex);
                agreementData.put("birthday", IdcardProUtil.getBirthDayFromIdCard((String) idCard));
                BigDecimal creditPrincipalAmount = agreementDataIdCardList.stream().filter(data -> data.get("creditPrincipalAmount") != null).map(data -> (BigDecimal) data.get("creditPrincipalAmount")).reduce(BigDecimal.ZERO, BigDecimal::add);//发放贷款本金金额
                BigDecimal lawsuitPrincipalAmount = agreementDataIdCardList.stream().filter(data -> data.get("lawsuitPrincipalAmount") != null).map(data -> (BigDecimal) data.get("creditPrincipalAmount")).reduce(BigDecimal.ZERO, BigDecimal::add);//发放贷款本金金额
                BigDecimal subtract = creditPrincipalAmount.subtract(lawsuitPrincipalAmount);
                if (lawsuitPrincipalAmount.compareTo(new BigDecimal(0)) == 0) {
                    agreementData.put("performance", "已履约");
                } else {
                    if (subtract.compareTo(new BigDecimal(0)) == 0) {
                        agreementData.put("performance", "从未履约");
                    } else {
                        agreementData.put("performance", "部分履约");
                    }
                }
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                try (ExcelWriter excelWriter = EasyExcel.write(output).withTemplate(environment.getProperty("file.evidence.url") + featureTable.getUrl()).excelType(ExcelTypeEnum.XLSX).build()) {
                    Workbook workbook = excelWriter.writeContext().writeWorkbookHolder().getCachedWorkbook();
                    if (CollectionUtil.isNotEmpty(featureTableExpandList)) {
                        //下拉或者ocr
                        for (FeatureTableExpand featureTableExpand : featureTableExpandList) {
                            String[] split = featureTableExpand.getSheetPage().split(",");
                            for (String s : split) {
                                Sheet sheet = workbook.getSheetAt(Integer.parseInt(s));
                                CellAddress address = new CellAddress(featureTableExpand.getLocation());
                                Row row = sheet.getRow(address.getRow());
                                //获取行
                                Cell cell = row.getCell(address.getColumn());
                                //获取列
                                cell.setCellValue((String) agreementData.get(featureTableExpand.getField()));
                            }
                        }
                    }
                    ExpressionParser parser = new SpelExpressionParser();
                    int numberSheet = workbook.getNumberOfSheets();
                    StandardEvaluationContext context = new StandardEvaluationContext();
                    MapAccessor propertyAccessor = new MapAccessor();
                    context.setVariables(agreementData);
                    context.setPropertyAccessors(Collections.singletonList(propertyAccessor));
                    TemplateParserContext templateParserContext = new TemplateParserContext("{{", "}}");
                    for (int i = 0; i < numberSheet; i++) {
                        WriteSheet writeSheet = EasyExcel.writerSheet(i).build();
                        Sheet sheet = workbook.getSheetAt(i);
                        Iterator<Row> rowIterator = sheet.rowIterator();
                        while (rowIterator.hasNext()) {
                            Row row = rowIterator.next();
                            Iterator<Cell> cellIterator = row.cellIterator();
                            while (cellIterator.hasNext()) {
                                Cell cell = cellIterator.next();
                                try {
                                    String templateValue = cell.getStringCellValue();
                                    SpelExpression expression = (SpelExpression) parser.parseExpression(templateValue, templateParserContext);
                                    expression.setEvaluationContext(context);
                                    cell.setCellValue((String) expression.getValue(agreementData));
                                } catch (Exception ignored) {

                                }
                            }
                        }
                        excelWriter.fill(agreementData, writeSheet);
                    }
                }
                Map<String, Object> map = new HashMap<>();
                byte[] outByte = output.toByteArray();
                map.put("templateName", String.format("%s-%s-%s.xlsx", agreementData.get("borrowerName"), agreementData.get("idcard"), featureTable.getName()));
                map.put("outByte", outByte);
                outList.add(map);
            }

        }
        String id = idWorker.generateId();
        String generatorUrl = String.format("%s/%s.zip", environment.getProperty("file.generator.url"), id);
        return generatorFile(outList, "/" + generatorUrl);
    }

    private BigDecimal convertFormalData(Map<String, Object> agreementData, List<FormulaData> formulaDataList, DocumentationRequest request) {
        if (StringUtil.isNotEmpty(request.getSueDate())) {
            agreementData.put("sueDate", request.getSueDate());
        }
        if(ObjectUtil.isNotEmpty(request.getDzName())){
            agreementData.put("dzName",request.getDzName());
            agreementData.put("dzMobile",request.getDzMobile());
        }
        if (StringUtil.isNotEmpty(request.getSueParameterId())) {
            Map<String, Object> sueMap = request.getSueMap();
            agreementData.put("formulaId", sueMap.get("formula_id"));
            agreementData.put("parameter1", sueMap.get("parameter1"));
            agreementData.put("parameter2", sueMap.get("parameter2"));
            agreementData.put("parameter3", sueMap.get("parameter3"));
            agreementData.put("parameter4", sueMap.get("days"));
        }
        if (CollectionUtil.isNotEmpty(request.getAgentList())) {
            agreementData.put("agentList", request.getAgentList());
        }
        if (StringUtil.isNotEmpty(request.getPlaintiffId())) {
            agreementData.putAll(request.getPlaintiffMap());
        }
        if (ObjectUtil.isNotEmpty(agreementData.get("sueDate"))) {
            //逾期公式有没有采用动态、如果没有则简单的1X2X（sue - 3） / day
            if (StringUtil.isEmpty((CharSequence) agreementData.get("formulaId"))) {
                try {
                    BigDecimal parameter1 = (BigDecimal) agreementData.get(agreementData.get("parameter1"));
                    BigDecimal parameter2 = (BigDecimal) agreementData.get(agreementData.get("parameter2"));
                    LocalDate parameter3 = LocalDate.parse(agreementData.get(agreementData.get("parameter3")).toString());
                    LocalDate currentDate = LocalDate.parse(agreementData.get("sueDate").toString());
                    Integer parameter4 = (Integer) agreementData.get("parameter4");
                    BigDecimal multiply = parameter1.multiply(parameter2);
                    Long days = DateTimeUtil.getLocalDateDiffDay(parameter3, currentDate);
                    return multiply.multiply(BigDecimal.valueOf(days)).divide(BigDecimal.valueOf(parameter4), RoundingMode.HALF_UP);
                } catch (Exception e) {
                    return BigDecimal.ZERO;
                }
            } else {
                //如果有动态采用则根据动态列表来获取对应处理的结果逻辑
                if (CollectionUtil.isEmpty(formulaDataList)) {
                    return BigDecimal.ZERO;
                } else {
                    List<FormulaData> dataFormalList = formulaDataList.stream().filter(formulaData -> StringUtil.equals((CharSequence) agreementData.get("formulaId"), formulaData.getFormulaId())).collect(Collectors.toList());
                    BigDecimal penaltyInterest = BigDecimal.ZERO;
                    LocalDate parameter3 = LocalDate.parse(agreementData.get(agreementData.get("parameter3")).toString());
                    LocalDate currentDate = LocalDate.parse(agreementData.get("sueDate").toString());
                    Long days = DateTimeUtil.getLocalDateDiffDay(parameter3, currentDate);
                    if (days < 0) {
                        //时间有误，则跳过
                        return BigDecimal.ZERO;
                    } else {
                        for (FormulaData formulaData : dataFormalList) {
                            //判断结束时间是否为空  为空改为当前时间
                            if (null == formulaData.getEndTime()) {
                                formulaData.setEndTime(LocalDate.now());
                            }
                            //如果逾期开始时间在公式结束时间后则跳过
                            if (parameter3.isAfter(formulaData.getEndTime())) {
                                continue;
                            }
                            LocalDate beforeTime = formulaData.getStartTime();
                            if (parameter3.isAfter(formulaData.getStartTime())) {
                                beforeTime = parameter3;
                            }
                            LocalDate afterTime = formulaData.getEndTime();
                            if (currentDate.isBefore(formulaData.getEndTime())) {
                                afterTime = currentDate;
                            }
                            BigDecimal parameter1 = (BigDecimal) agreementData.get(agreementData.get("parameter1"));
                            int p4 = (Integer) agreementData.get("parameter4");

                            Long diffDay = DateTimeUtil.getLocalDateDiffDay(beforeTime, afterTime);
                            penaltyInterest = penaltyInterest.add(parameter1.multiply(formulaData.getRate()).multiply(BigDecimal.valueOf(diffDay)).divide(BigDecimal.valueOf(p4), 2, RoundingMode.HALF_UP));
                        }
                        return penaltyInterest.setScale(2, RoundingMode.HALF_UP);
                    }
                }
            }
        } else {
            //没有设置逾期暂计金额则为0
            return BigDecimal.ZERO;
        }
    }

    private Result generatorFile(List<Map<String, Object>> outList, String generatorUrl) throws IOException {
        ZipOutputStream out = null;
        OutputStream os = null;
        try {
            File file1 = new File(environment.getProperty("file.evidence.url") + generatorUrl);
            if (!file1.exists()) {
                File fileParent = new File(file1.getParent());
                fileParent.mkdirs();
            }
            os = Files.newOutputStream(Paths.get(environment.getProperty("file.evidence.url") + generatorUrl));
            byte[] buffer = new byte[1024];
            //生成的ZIP文件名为Demo.zip
            out = new ZipOutputStream(os);
            //需要同时下载的两个文件result.txt ，source.txt
            for (Map<String, Object> map : outList) {
                InputStream fis = new ByteArrayInputStream((byte[]) map.get("outByte"));
                out.putNextEntry(new ZipEntry((String) map.get("templateName")));
                int len;
                //读入需要下载的文件的内容，打包到zip文件
                while ((len = fis.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
                out.closeEntry();
                fis.close();
            }
        } finally {
            IOUtil.close(out, os);
        }

        return Result.ok(generatorUrl);
    }
}
